<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>新建销售单 </title>
    <link href="../../css/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<script src="../../js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../js/jquery.easyui.min.js" type="text/javascript"></script>
<script src="../../js/keys.js" type="text/javascript"></script>
<script src="../../js/ChinesePY.js" type="text/javascript"></script>
<script src="../../js/util.js" type="text/javascript"></script>
<script src="../../js/comm.js" type="text/javascript"></script>
<script src="../../js/JBusinessCom.js" type="text/javascript"></script>
<script src="../../js/JPageController.js" type="text/javascript"></script>
<script src="../../js/My97DatePicker/WdatePicker.js" type="text/javascript"></script>
<div id="loading"></div>
<table style="min-width: 882px;" width="100%" border="0" height="100%" cellspacing="0" cellpadding="0">
<tr>
<td valign="top" bgcolor="#e6e6e8" class="main">
<script src="../../js/jquery.autocomplete.min.js" type="text/javascript"></script>
<style type="text/css">
    .tipDiag {
        position: absolute;
        padding: 3px;
        font-size: 12px;
        border: 1px solid #F00;
        background: #FFF8CB url(../../images/warning.png) no-repeat 3px 3px;
        color: #000;
        display: none;
        padding-left: 16px;
    }

    .htd {
        background-color: #fdf7f7;
        text-align: center;
    }
</style>
<!--data-val:是否需要客户端验证-->
<!--data-val-required:验证类型和错误消息-->

<input data-val="true" data-val-required="SaleId 字段是必需的。" id="SaleId"  name="SaleId" type="hidden" value="00000000-0000-0000-0000-000000000000"/>
<input data-val="true" data-val-number="字段 IsToList 必须是一个数字。" data-val-required="IsToList 字段是必需的。" id="IsToList" name="IsToList" type="hidden" value="0"/>
<input data-val="true" data-val-number="字段 IsPrint 必须是一个数字。" data-val-required="IsPrint 字段是必需的。" id="IsPrint" name="IsPrint" type="hidden" value="0"/>
<input id="IsOpenProductSN" name="IsOpenProductSN" type="hidden" value="0"/>
<input type="hidden" name="hidProductsSn"/>
<table width="100%" border="0" cellspacing="0" cellpadding="0" height="500">
<tr>
<td valign="top">
<div class="buttonArea">
    <div class="left">
        <a class="button blueButton" onclick="SaveDataToList(1);">保存并新增</a><a class="button"
                                                                       onclick="SaveDataToList(0);">保存</a>
    </div>
    <!-- left -->
    <div class="right">
        <a class="button greenButton" onclick="parent.childAddTab('销售历史','Sale/List.html','慧管货')">历史单据</a>
    </div>
    <!-- right -->
</div>
<!-- buttonArea -->
<div class="clear height10"></div>
<div class="shadowBoxWhite receipts">
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="title">
    <tr>
        <td width="30%" height="50">&nbsp;</td>
        <td width="40%" align="center" valign="top" class="text">商品销售单</td>
        <td width="30%" align="right" valign="bottom" class="font999" style="padding-bottom: 20px;">
            单据编号：<input class="codeEdit" id="SaleNo" name="SaleNo" onchange="calSaleNo()" type="text"
                        value=""/></td>
    </tr>
</table>
<div class="clear height10"></div>
<table width="100%" cellspacing="0" cellpadding="0" id="SaleInfo">
    <tr>
        <td width="30">客户</td>
        <td width="200"><select  data-val="true" class="wf100 inputSelect"
                                data-val-required="请选择客户"
                                id="ClientId" name="ClientId" style="width:200px">
        </select></td>
        <td width="60" align="right">出库仓库&nbsp;</td>
        <td width="120"><select data-val="true" onchange="WarehouseChaneg()" class="wf100 inputSelect" data-val-required="请选择仓库" id="WarehouseId"
                                name="WarehouseId" style="width:120px">
        </select></td>
        <td width="60" align="right">是否送货&nbsp;</td>
        <td width="40" align="left">
            <input name="IsNeedDeliverGoods" onclick="chgDeliverGoods()" type="checkbox" value="1"/></td>
        <td width="60" align="right" style="display:none;" id="IsOpenSaleTaxRate_1">免税</td>
        <td width="20" align="left" style="display:none;" id="IsOpenSaleTaxRate_10">
            <input type="checkbox" name="chkNoTaxRate" id="chkNoTaxRate" onclick="chgNoTaxRate()"
                   value="1"/></td>
        <td width="60" align="right">经手人&nbsp;</td>
        <td width="100"><select class="inputSelect" data-val="true" data-val-required="请选择销售员" id="SaleUser"
                                name="SaleUser">

        </select></td>
        <td width="80" align="right">业务日期&nbsp;</td>
        <td width="120"><input class="inputText data" data-val="true" data-val-required="请选择销售日期"
                               id="SaleDate" name="SaleDate" onClick="WdatePicker()" readonly="true"
                               type="text" value="2013-12-03"/></td>

    </tr>
</table>
<div class="clear height10"></div>
<div class="deliver" id="deliverGoods" style="display: none;">
    <span class="fl">送货日期：</span>
                        <span class="fl">
                            <input class="inputText" data-val="true" data-val-required="请选择送货日期" id="ReceDate"
                                   name="ReceDate" onClick="WdatePicker()" readonly="true" size="10" type="text"
                                   value="2013-12-03"/></span>

    <span class="fl">客户联系人：</span>
                        <span class="fl">
                            <input class="inputText" id="ClientLink" maxlength="100" name="ClientLink" size="10"
                                   type="text" value=""/></span>

    <span class="fl">联系电话：</span>
                        <span class="fl">
                            <input class="inputText" id="ClientTel" maxlength="100" name="ClientTel" size="10"
                                   type="text" value=""/></span>

    <span class=" fl">送货地址：</span>
                        <span class="fl">
                            <input class="inputText" id="ReceAddress" maxlength="100" name="ReceAddress" size="35"
                                   type="text" value=""/></span>
                        <span class="fl">
                            <input name="IsUpdateClientCon" type="checkbox" value="1"/></span>
    <span class="fl">同步到客户信息</span>
</div>
<!-- deliver -->
<div class="clear height10"></div>
<div class="tableDiv">
    <table width="100%" border="0" cellspacing="1" cellpadding="5" id="tabProducts">
        <tr>
            <th width="60" height="60" align="center" valign="middle">序号</th>
            <th align="left" valign="middle">商品名称/规格</th>
            <th width="150" align="center" valign="middle">商品编号</th>
            <th width="60" align="center" valign="middle">单价(元)</th>
            <th width="65" align="center" valign="middle">数量</th>
            <th width="50" align="center" valign="middle">单位</th>
            <th width="100" align="center" valign="middle">金额(元)</th>
            <th width="60" align="center" valign="middle" id="IsOpenSaleTaxRate_2" style="display:none;">税率(%)</th>
            <th width="100" align="center" valign="middle" id="IsOpenSaleTaxRate_3" style="display:none;">税后金额(元)</th>
            <th width="80" align="left" valign="middle">备注</th>
        </tr>
        <tr id="trTmp" style="display:none;">
            <td align="center" valign="middle" bgcolor="#FFFFFF">
                <span id="orderdiv" class="num"></span>
                            <span class="actionArea"><a href="javascript:;" class="plusLite"
                                                        onclick="addRow(this);InitOrder();"></a><a href="javascript:;"
                                                                                                   class="delLite"
                                                                                                   onclick="deleteRow(this);"></a></span>
            </td>
            <td align="left" valign="middle" bgcolor="#FFFFFF">
                <table width="100%" cellpadding="0" cellspacing="0" border="0" class="chose">
                    <tr>
                        <td>
                            <input style="text-align: left;" type="text" class="receiptsInputText"
                                   autocomplete="off" name="showProductName"/></td>
                        <td width="50" align="right"><a class="choseGoods" style="display: none;"
                                                        onclick="SelectWareProductByBusi(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode,
                                                        'Sale',$('#WarehouseId').find('option:selected').val(),$('#IsOpenProductSN').val())">选择</a>
                        </td>
                    </tr>
                </table>
            </td>
            <td align="left" valign="middle" bgcolor="#FFFFFF">
                <input type="hidden" name="hidProductId"/>
                <input type="hidden" name="hidLowPrice"/>
                <input type="hidden" name="hidStockCount"/>
                <input type="text" style="width: 145px;" class="receiptsInputText" autocomplete="off"
                       name="showProductCode"/></td>
            <td align="center" valign="middle" bgcolor="#FFFFFF">
                <input type="text" style="width: 50px;" class="receiptsInputText" name="SalePrice" maxlength="10"
                       onchange="checkSalePrice(this);calSaleAmt(this);"/>
            </td>
            <td align="center" valign="middle" bgcolor="#FFFFFF">
                <input type="text" style="width: 40px;" class="receiptsInputText" name="SaleCount"  maxlength="10"
                       onchange="calSaleAmt(this)"/>
                <input type="hidden" name="hidSerialId"/>
                <input type="hidden" name="hidSNManage"/>
                <a href="javascript:;" name="aSingleSN" style="display: none;" class="sn" onclick="SingleSelectSerialNo($(this).parent().parent().find('input[name=\'hidProductId\']').val(),$(this).parent().parent().find('input[name=\'hidSerialId\']').attr('id').replace('sn_',''),$('#WarehouseId').find('option:selected').val(), 'Sale','addPage');"></a>
            </td>
            <td align="center" valign="middle" bgcolor="#FFFFFF">
                <input type="text" style="width: 40px;" class="receiptsInputText" name="UnitName"/>
                <input type="hidden" name="HidUnitCode"/>
                <input type="hidden" name="HidIsDecimal" value="1"/></td>
            <td align="center" valign="middle" bgcolor="#FFFFFF">
                <input type="text" style="width: 90px;" class="receiptsInputText" name="EachSaleAmt"  maxlength="10"
                       onchange="calSalePrice(this)"/></td>
            <td align="center" valign="middle" style="width: 60px;display:none;" bgcolor="#FFFFFF"
                id="IsOpenSaleTaxRate_4">
                <input type="text" class="receiptsInputText" name="EachTaxRate" maxlength="10" id="EachTaxRate" onchange="calSaleAmt(this)"
                       style="width: 60px"/></td>
            <td align="center" valign="middle" style="width: 90px;display:none;" bgcolor="#FFFFFF"
                id="IsOpenSaleTaxRate_5">
                <input type="text" class="receiptsInputText" name="EachAfterTaxAmt" readonly="readonly" onchange="calCountAmt()"
                       style="width: 90px"/></td>
            <td align="left" valign="middle" bgcolor="#FFFFFF">
                <input type="hidden" name="hidLendDetailId"/>
                <input style="text-align: left; width: 70px;" type="text" class="receiptsInputText"
                       name="EachSaleRemark" maxlength="200"/></td>
        </tr>
        <tr id="total">
            <td width="60" align="center" valign="middle" bgcolor="#FFFFFF" class="font14">合计</td>
            <td align="center" valign="middle" bgcolor="#FFFFFF"></td>
            <td width="150" align="left" valign="middle" bgcolor="#FFFFFF"></td>
            <td width="60" align="center" valign="middle" bgcolor="#FFFFFF"></td>
            <td width="50" align="center" valign="middle" bgcolor="#FFFFFF"><span
                    id="spanTotalCount"></span></td>
            <td width="50" align="center" valign="middle" bgcolor="#FFFFFF"></td>
            <td width="100" align="center" valign="middle" bgcolor="#FFFFFF"><span
                    class="fontRed">￥</span><span class=" font18 fontRed" id="beforeTaxAmt"></span>
                                    <input data-val="true" data-val-number="字段 SaleAmt 必须是一个数字。" class=" font18 fontRed"
                                           data-val-range="数值超出合理的范围。" data-val-range-max="9999999999"
                                           data-val-range-min="0" data-val-regex="金额格式不正确。"
                                           data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                                           data-val-required="SaleAmt 字段是必需的。" id="SaleAmt" name="SaleAmt"
                                           onclick="$(this).blur()" readonly="true" size="12"
                                           style="width:70px;color:Red;background-color:transparent;" type="text"
                                           value="0"/></td>
            <td width="60" align="center" valign="middle" bgcolor="#FFFFFF" style="display: none;"
                id="IsOpenSaleTaxRate_6"></td>
            <td width="90" align="center" valign="middle" bgcolor="#FFFFFF" style="display: none;"
                id="IsOpenSaleTaxRate_7"><span
                    class="fontRed">￥</span><span id="spanTaxAmt" class=" font18 fontRed">0.00</span></td>
            <td width="80" align="center" valign="middle" bgcolor="#FFFFFF"></td>
        </tr>
        <tr>
            <td valign="middle" align="center" bgcolor="#FFFFFF" class="font14">备注</td>
            <td colspan="1" bgcolor="#FFFFFF" id="form_txt">
                <textarea class="receiptsInputText textl" maxlength="400" cols="20" id="SaleRemark" name="SaleRemark"
                          rows="2" style="height:40px;"></textarea>　
            </td>
            <td colspan="5" bgcolor="#FFFFFF" id="form_txt_1">
                <table width="100%" border="0" cellspacing="0" cellpadding="3">
                    <tr>
                        <td align="right">结算方式：</td>
                        <td width="120">
                            <select style="width: 80px" data-val="true" data-val-required="请选择收款账户" id="AccountId"
                                    name="AccountId" class="inputSelect">
                            </select>
                        </td>
                        <td align="right" width="60" id="IsOpenSaleTaxRate_8" style="display: none;">税额：</td>
                        <td width="60" id="IsOpenSaleTaxRate_9" style="display: none;" >
                            <span id="spanTotalTaxAmt">0</span>
                            <input data-val="true" data-val-number="字段 spanTotalTaxAmt 必须是一个数字。"
                                   data-val-range="数值超出合理的范围" data-val-range-max="9999999999"
                                   data-val-range-min="0" data-val-regex="折后应收金额格式不正确。"
                                   data-val-regex-pattern="^(-?\d+)(\.\d+)?$" id="totalTaxAmt"
                                   name="totalTaxAmt" type="hidden" value="0"/>
                            元
                        </td>
                    </tr>
                    <tr>
                        <td width="100" align="right">折 扣 率：</td>
                        <td width="120">
                            <input class="inputBorder" data-val="true"
                                   data-val-number="字段 DiscountRate 必须是一个数字。" data-val-range="数值超出合理的范围"
                                   data-val-range-max="9999999999" data-val-range-min="0"
                                   data-val-regex="折扣率格式不正确。" data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                                   id="DiscountRate" name="DiscountRate" onchange="calDiscountAmt()"
                                   size="8" type="text" value="100"/>
                            %
                        </td>
                        <td width="80" align="right">折后应收：</td>
                        <td width="120">
                            <input class="inputBorder" data-val="true"
                                   data-val-number="字段 DiscountAmt 必须是一个数字。" data-val-range="数值超出合理的范围"
                                   data-val-range-max="9999999999" data-val-range-min="0"
                                   data-val-regex="折后应收金额格式不正确。" data-val-regex-pattern="^(-?\d+)(\.\d+)?$"
                                   id="DiscountAmt" name="DiscountAmt" onchange="calDiscountRate()" size="8"  maxlength="10"
                                   type="text" value="0"/>
                            元
                        </td>
                    </tr>
                    <tr>
                        <td align="right">其他费用：</td>
                        <td>
                            <input class="inputBorder" data-val="true"
                                   data-val-number="字段 OtherFee 必须是一个数字。" data-val-regex="其他费用格式不正确。"
                                   data-val-regex-pattern="^(-?\d+)(\.\d+)?$" data-val-required="请输入本次其他费用"
                                   id="OtherFee" name="OtherFee" onchange="calOtherFeeAmt()" size="8"  maxlength="10"
                                   type="text" value="0"/>
                            元
                        </td>
                        <td align="right">应收金额：</td>
                        <td>
                            <span id="spanFAReceAmt">0</span>
                            <input data-val="true" data-val-number="字段 FAReceAmt 必须是一个数字。"
                                   data-val-range="数值超出合理的范围" data-val-range-max="9999999999"
                                   data-val-range-min="0" data-val-regex="折后应收金额格式不正确。"
                                   data-val-regex-pattern="^(-?\d+)(\.\d+)?$" id="FAReceAmt"  maxlength="10"
                                   name="FAReceAmt" type="hidden" value="0"/>
                            元
                        </td>
                    </tr>
                </table>
            </td>
            <td width="80" bgcolor="#FFFFFF">
                <div class="font16 fontOrange" style="line-height: 25px;">实收金额：</div>
                <input class="inputBorder" data-val="true" data-val-number="字段 ReceAmt 必须是一个数字。"
                       data-val-range="数值超出合理的范围" data-val-range-max="9999999999" data-val-range-min="0"
                       data-val-regex="实收金额格式不正确。" data-val-regex-pattern="^(-?\d+)(\.\d+)?$" id="ReceAmt"
                       name="ReceAmt" size="10" type="text" value="0"/>
            </td>
        </tr>
    </table>
</div>
<!-- tableDiv -->
<div class="bottomButtonArea">
    <div class="left font999">制单人：<span id="buildUser"></span>&nbsp;&nbsp;&nbsp;&nbsp;制单时间：<span id="buildTime"></span>
    </div>
    <div class="right">
        <a class="button" id="add" style="display: none" onclick="closethistab('新增销售');">取消</a>
        <a class="button" id="copyAdd" style="display: none" onclick="closethistab('复制新增销售单');">取消</a>
        <a class="button" onclick="SaveDataToList(0);">保存</a>
        <a class="button blueButton" onclick="SaveDataToList(1);">保存并新增</a>

    </div>
</div>
<!-- buttonArea -->
</div>
<!-- receipts -->
    </td>
    </tr>
    </table>
<input type="hidden" id="hidSaleChooseGoods" value=""/>
</td>
</tr>
</table>

</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
       //首先检查权限
    var result = checkAuthority("Sale/SaveSale");
    if (!result){
        //给出提示信息
        Dialog.alert("对不起，您无操作权限!");
        //关闭当前页面
        parent.CloseTabByTitle("新增销售");
        return;
    }
});
var copyAdd = "";
var autoSaleList;
$(document).ready(function(){
    copyAdd = requestUrlPara("list");
    if(copyAdd == "copyAdd"){
         var reqJson = {};
         var saleId = requestUrlPara("saleId");
         reqJson["SaleId"] = saleId;
         var result = parent.sale_bi.querySaleDetail(JSON.stringify(reqJson));
         autoSaleList = eval("(" + result +")");

    }
    if(copyAdd == "copyAdd"){
        $("#copyAdd").show();
    }else{
        $("#add").show();
    }
});
$(document).ready(function () {
    //智能匹配支持拼音
    $('.easyui-combobox').combobox({
        filter: function (q, row) { // q是你输入的值，row是数据集合

            var opts = $(this).combobox('options');
            var optField = row[opts.textField].toLowerCase();
            var potFieldPY = Pinyin.GetQP(row[opts.textField]).toLowerCase();
            var potFieldPYJ = Pinyin.GetJP(row[opts.textField]).toLowerCase();
            var ql = q.toLowerCase();
            var qlPY = Pinyin.GetQP(q).toLowerCase();
            return optField.indexOf(ql) >= 0 || potFieldPY.indexOf(qlPY) >= 0 || potFieldPYJ.indexOf(qlPY) >= 0; // 同一转换成小写做比较，==0匹配首位，>=0匹配所有
        }
    });
    initForm();
});
var IsOpenSaleTaxRate = 0;
var autoCompleteIndex = 0;

//复制新增自动填充数据
function selectData(trTmp){
        var resultList = autoSaleList["EachData"][autoCompleteIndex];
        trTmp.children("td").eq(1).find('input[name="showProductName"]').val(resultList["ProductName"] + "/" + resultList["ProductForm"])
        trTmp.children('td').eq(1).find('input[name="showProductName"]').attr("readonly", "readonly");
        trTmp.children('td').eq(1).find('input[name="showProductName"]').attr("unselectable", "on");
        trTmp.children('td').eq(4).find('input[name="hidSNManage"]').val(resultList["SNManage"]);
        trTmp.children("td").eq(2).find('input[name="showProductCode"]').val(resultList["ProductCode"])
        trTmp.children('td').eq(2).find('input[name="showProductCode"]').attr("readonly", "readonly");
        trTmp.children('td').eq(2).find('input[name="hidStockCount"]').val(resultList["StockCount"]);
        trTmp.children('td').eq(2).find('input[name="hidLowPrice"]').val(resultList["LowSalePrice"]);
        trTmp.children('td').eq(1).find('input[name="showProductCode"]').attr("unselectable", "on");
        trTmp.children("td").eq(3).find('input[name="SalePrice"]').val(resultList["SalePrice"])
        trTmp.children("td").eq(4).find('input[name="SaleCount"]').val(resultList["SaleCount"])
        trTmp.children("td").eq(5).find('input[name="UnitName"]').val(resultList["UnitName"])
        trTmp.children('td').eq(5).find('input[name="UnitName"]').attr("readonly", "readonly");
        trTmp.children('td').eq(5).find('input[name="UnitName"]').attr("unselectable", "on");
        trTmp.children('td').eq(5).find('input[name="HidUnitCode"]').val(resultList["ProductUnit"]);
        trTmp.children('td').eq(5).find('input[name="HidIsDecimal"]').val(resultList["IsDecimal"]);
        trTmp.children("td").eq(6).find('input[name="EachSaleAmt"]').val(resultList["SaleAmt"])
        trTmp.children("td").eq(7).find('input[name="EachTaxRate"]').val(resultList["TaxRate"])
        trTmp.children("td").eq(8).find('input[name="EachAfterTaxAmt"]').val(resultList["AfterTaxAmt"])
        trTmp.children("td").eq(9).find('input[name="EachSaleRemark"]').val(resultList["SaleRemark"])
        trTmp.children("td").eq(2).find("input:hidden[name='hidProductId']").val(resultList["ProductId"])
        if (resultList["SNManage"] != "0"&& productSn == 1) {
            if(resultList["SNManage"] == "1"){
                trTmp.children("td").eq(4).find('input[name="SaleCount"]').val(0).change();
                trTmp.children("td").eq(4).find('input[name="SaleCount"]').attr("readonly","readonly");
            }
            trTmp.children('td').eq(4).find('a[name="aSingleSN"]').show();
            trTmp.find('input[name="hidSerialId"]').attr("id", 'sn_'+autoCompleteIndex+resultList["ProductId"])
        } else {
            trTmp.children('td').eq(4).find('a[name="aSingleSN"]').hide();
        }
       autoCompleteIndex++;
}
//复制新增自动填充金额数据
function calAmtData(){
    var reqJson = {};
    reqJson["SaleId"] = requestUrlPara("saleId");
    var result = parent.sale_bi.queryCpSaleBySaleId(JSON.stringify(reqJson));
    var resultList = eval("(" + result +")");
    $("#SaleRemark").val(resultList["SaleRemark"]);
    $("#DiscountRate").val(resultList["DiscountRate"]);
    $("#AccountId").val(resultList["AccountId"]);
    $("#WarehouseId").val(resultList["WareHouseId"]);
    $("#ClientId").val(resultList["ClientId"]);
    $("#SaleUser").val(resultList["SaleUser"]);
//    $("#DiscountAmt").val(resultList["DisCountAmt"]);
    $("#OtherFee").val(resultList["OtherFee"]);
//    $("#SaleAmt").val(resultList["SaleAmt"]);
}

var saleTaxRate = 0;
var IsCheckSalePrice = 0;
var productSn = 0;

function initForm() {
    // 初始化销售单数据
    var billNo = queryBillNoByType(4);
    $('#SaleNo').val(billNo);
    //var sysconf = getSysConfig();
    //sysconf = eval("(" + sysconf + ")");
   // var saleConfig = getSysConfigByCode("IsOpenSaleTaxRate");
   // var saleFun = eval("(" + saleConfig + ")");
   // saleTaxRate = saleFun["TaxRate"]
    //if(saleTaxRate == undefined){
      //  saleTaxRate = 0;
    //}
//
    // {u'IsAllowLookOtherList': u'1', u'IsOpenSaleTaxRate': u'1', u'IsOpenBuyTaxRate': u'1', u'IsCheckSalePrice': u'0', u'IsAllowNegativeInventory': u'1', u'IsOpenProductNum': u'1'}
    //$('#IsOpenProductSN').val(sysconf['IsOpenProductNum']);
    //IsOpenSaleTaxRate = sysconf['IsOpenSaleTaxRate'];
    //IsCheckSalePrice = sysconf['IsCheckSalePrice'];
   // productSn = sysconf['IsOpenProductNum'];
   // if(IsOpenSaleTaxRate == undefined){
    //    IsOpenSaleTaxRate = 0
   // }
   // if(IsCheckSalePrice == undefined){
    ///    IsCheckSalePrice = 0
   // }
   // if(productSn == undefined){
   //     productSn = 0
   // }
       var IsOpenSaleTaxRate = '0';
    if ('1' == IsOpenSaleTaxRate) {
        $('#IsOpenSaleTaxRate').show()
        $('#IsOpenSaleTaxRate_1').show()
        $('#IsOpenSaleTaxRate_2').show()
        $('#IsOpenSaleTaxRate_3').show()
        $('#IsOpenSaleTaxRate_4').show()
        $('#IsOpenSaleTaxRate_5').show()
        $('#IsOpenSaleTaxRate_6').show()
        $('#IsOpenSaleTaxRate_7').show()
        $('#IsOpenSaleTaxRate_8').show()
        $('#IsOpenSaleTaxRate_9').show()
        $('#IsOpenSaleTaxRate_10').show()

        $('#form_txt').attr('colspan', '2');
        $('#form_txt_1').attr('colspan', '6');
    }
    $('#SaleDate').val(getNowTime());
    $('#ReceDate').val(getNowTime());
    $('#buildTime').html(buildTime());
    $('#buildUser').html("test");
    
  
    //try {

       // var wh_list = parent.client_bi.queryClientDropDownList("{}");
       // wh_list = eval("(" + wh_list + ")");
       // $('#ClientId').html(buildSelectOption(wh_list['Data'], 'ClientId', 'ClientName', false));
       // var wh_list = parent.warehouse_bi.queryWarehouseDropDownList("{}");
       // wh_list = eval("(" + wh_list + ")");
       // $('#WarehouseId').html(buildSelectOption(wh_list['Data'], 'WarehouseId', 'WarehouseName', false));
       // wh_list = parent.common_bi.getOperatorList("{}");
       // wh_list = eval("(" + wh_list + ")");
       // $('#SaleUser').html(buildSelectOption(wh_list['Data'], 'Value', 'Text', false))
       // $('#SaleUser').val(wh_list["LoginUserId"])
       // wh_list = parent.account_bi.queryAccountDropDownList("{}");
       // wh_list = eval("(" + wh_list + ")");
       // $('#AccountId').html(buildSelectOption(wh_list['Data'], 'Value', 'Text', false))
       // $('#ClientId').change(function(){
       //      GetClientAddress();
       // })
        var saleId = "00000000-0000-0000-0000-000000000000";
        console.log("**************")
        if (saleId == '00000000-0000-0000-0000-000000000000') {
        	  console.log("**************")
            //验证权限
           // var isAudit = checkPermByCode('PERM_ADD');
            //if (!isAudit) {
              //  Dialog.alert("非常抱歉，您没有权限访问该页面!", function () {
               //     window.location.href = "List.html";
               // });
              //  return;
           // }//
           // if(!validateSobState()){
             //   return;
           // }
           
           /*
            if(autoSaleList != null){
                if(autoSaleList["EachData"].length > 0){
                    for(var i = 0; i < autoSaleList["EachData"].length; i++){
                        addRow();
                        if(i == autoSaleList["EachData"].length-1){
                            copyAdd = "";
                        }
                    }
                }
                calAmtData();
                calCountAmt();
                InitOrder();
                WarehouseChaneg();
            }else{
                addRow();
                addRow();
            }*/
            addRow();
            addRow();
            addRow();
        }



        InitOrder();
        GetClientAddress();
        //打印
        var rememberPrint = "0";
        var isPrint = requestUrlPara("IsPrint");
        if (isPrint == 1) {
            $("#chkPrint").attr("checked", "checked");
        } else if (isPrint == 0) {
            if (rememberPrint == "1") {
                $("#chkPrint").attr("checked", "checked");
            } else if (rememberPrint == "0") {
                $("#chkPrint").removeAttr("checked");
            }
        }
        var printSaleId = requestUrlPara("SaleId");
        var isToList = requestUrlPara("IsToList");
        if (isToList == 1) {
            parent.childAddTab('销售历史', '/Sale/List?IsPrint=' + isPrint + '&SaleId=' + printSaleId + "&IsToList=" + isToList, '慧管货');
        } else if (isPrint == 1) {
            OpenPrint('/Sale/Print?SaleId=' + printSaleId);
        }
   // } catch (e) {
    //    Dialog.alert(e);
    //}
}


function calSaleNo() {
        var saleNo = $("#SaleNo").val().trim();
        if (saleNo == "") {
            Dialog.alert("请输入单据编号");
            $('#SaleNo')[0].focus();
            return;
        };
        if (!CheckWord(saleNo)) {
            return;
        }
        var temp = ValidateNo(saleNo);
        if (temp == "0") {
            Dialog.alert("单据编号重复");
            $('#SaleNo')[0].focus();
            return;
        }
}

function GetClientAddress() {
    var clientId = $("#ClientId").val();
    if (clientId != "" && clientId != null) {
        requestJson = {};
        requestJson["clientId"] = clientId;
        var data = parent.common_bi.getClientUserInfo(JSON.stringify(requestJson));
        data = eval("(" + data + ")");

        var dataArr = data['Data'];
        if (dataArr.length == 1) {
            dataArr = dataArr[0];
            $("#ReceAddress").val(dataArr['ClientAddress']);
            $("#ClientLink").val(dataArr['ClientLink']);
            $("#ClientTel").val(dataArr['ClientTel']);
        }
    }
    else {
        $("#ReceAddress").val("");
    }
}

//显示和隐藏送货地址
function chgDeliverGoods() {
    var isNeed = document.getElementsByName("IsNeedDeliverGoods")[0];
    var reqJson = {};
    if (isNeed.checked) {
        $("#deliverGoods").show();
        var ClientId = ($('#ClientId').val()) == null?"":$('#ClientId').val();
        reqJson["ClientId"] = ClientId;
        var resultList = parent.client_bi.getClientInfo(JSON.stringify(reqJson));
        var result = eval("(" + resultList +")")
         $("#ClientLink").val(result["ClientLink"]);
         $("#ClientTel").val(result["ClientTel"]);
         $("#ReceAddress").val(result["ClientAddress"]);
    }
    else {
        $("#deliverGoods").hide();
    }
}

function addRow(obj) {
    var trTmp = $("#trTmp").clone();
    var tempRow = document.getElementById("trTmp");
    var temRowIndex = 0;
   //判断是不是复制新增
    if(copyAdd == "copyAdd"){
        selectData(trTmp);
    }
    trTmp.attr("id", "");
    trTmp.show();
    if (obj == null) {
        trTmp.insertBefore($("#trTmp"));
        obj = trTmp;
        obj.rowIndex = tempRow.rowIndex - 1;

    } else {
        trTmp.insertAfter(obj.parentNode.parentNode.parentNode);
        temRowIndex = obj.parentNode.parentNode.parentNode.rowIndex + 1;
        obj = trTmp;
        obj.rowIndex = temRowIndex;
    }

    var autoCompleteTextbox = trTmp.find("input:text[autoComplete='off']");
    if (!!autoCompleteTextbox) {
        try {
            //智能提示
            var productheader = { ProductCode: "商品编号", ProductName: "商品名称" };
            autoCompleteTextbox.each(function () {
                $(this).autoComplete({
                    header: productheader,
                    data_fun: ato_sel_data,
                    width: 400,
                    selected: function (o) {
                        requestJson = {};
                        requestJson["warehouseId"] = $('#WarehouseId').find('option:selected').val();
                        requestJson["productId"] = o.ProductId;
                        var r = parent.shared_bi.getProductStock(JSON.stringify(requestJson));
                        if (null != r && 'None' != r) {
                            o.Store = r;
                        }
                        var jsonn = [];
                        var value = {
                            "ID": o.ProductId,
                            "Code": o.ProductCode,
                            "Name": o.ProductName,
                            "Form": o.ProductForm == 'None' ? '' : o.ProductForm,
                            "Class": o.Class,
                            "Unit": o.Unit,
                            "Store": o.Store,
                            "CostPrice": o.ProductCostPrice,
                            "SalePrice": o.ProductSalePrice,
                            "UnitCode": o.UnitCode,
                            "IsDecimal": o.IsDecimal,
                            "LowSalePrice": o.LowSalePricePer,
                            "HigSalePrice": o.HighSalePricePer,
                            "SNManage": o.SNManage,
                            "RowId": guidGenerator(),
                            "SaleCount": o.SNManage != 1?1:0
                        };
                        jsonn.push(value);
                        SelectProductOK(jsonn, obj);
                        //打开序列号管理
                        if (jsonn[0]["SNManage"] == "1" && productSn == '1') {
                            SingleSelectSerialNo($(obj).find('input[name=\'hidProductId\']').val(), $(obj).find('input[name=\'hidSerialId\']').attr('id').replace('sn_', ''), $('#WarehouseId').find('option:selected').val(), 'Sale','addPage');
                        }
                    }
                });
            });
        } catch (e) {
            alert(e);
        }
    }
    $("#tabProducts tr").mouseover(function () {
        $(this).find('.choseGoods').show();
    }).mouseout(function () {
                $(this).find('.choseGoods').hide();
            })
}

function ato_sel_data(key) {
    requestJson = {};
    requestJson["WarehouseId"] = $('#WarehouseId').find('option:selected').val();
    requestJson["Key"] = key;
    var ato_data = parent.shared_bi.queryProduct(JSON.stringify(requestJson));
    ato_data = eval("(" + ato_data + ")");
    if (ato_data['IsSuccess'] == 1) {
        return ato_data['Data'];
    }
    return [];
}


function unLockState() {

}

function InitOrder() {
    var rows = $("#tabProducts tr");
    var orders = 1;
    for (var i = 0; i < rows.length; i++) {
        if ($(rows[i]).children('td').eq(2).find('input[type="hidden"]').length == 3 && $(rows[i]).attr("id") != "trTmp") {
            $(rows[i]).children('td').eq(0).children('#orderdiv').text(orders);
            orders++;
        }
    }
}

//删除行
function deleteRow(obj) {
    obj.parentNode.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode.parentNode);
    if ($("#tabProducts tr[id!='trTmp']").find("input:text[autoComplete='off']").length <= 1) {
        addRow();
    }
    $("#tabProducts tr[id!='trTmp']").find("input:text[autoComplete='off']").first().focus();
    //计算总金额
    calCountAmt();
    InitOrder();
}

//计算总金额
function calCountAmt() {
    //var amtNode = $("input[name='EachSaleAmt']");
    var amtCount = 0;
    var totalCount = 0;
    var rateAmt = 0;
    var rows = $("#tabProducts tr");
    var isOpenTax = IsOpenSaleTaxRate;
    for (var j = 0; j < rows.length; j++) {
        var productName = $(rows[j]).children('td').eq(1).find('input[name="showProductName"]').val();
        var eachAmt = $(rows[j]).children('td').eq(6).find('input[name="EachSaleAmt"]').val();
        var eachCount = $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').val();
        var SNManage = $(rows[j]).children('td').eq(4).find('input[name="hidSNManage"]').val();
        if (typeof (productName) != 'undefined' && productName != '' && typeof (eachAmt) != 'undefined' && eachAmt != '') {
            amtCount = amtCount + Number(eachAmt);
            totalCount = totalCount + Number(eachCount);
        }
        if (isOpenTax == "1") {
            var eachAfterRateAmt = $(rows[j]).children('td').eq(8).find('input[name="EachAfterTaxAmt"]').val();
            if (typeof (eachAfterRateAmt) != 'undefined' && eachAfterRateAmt != '') {
                rateAmt = rateAmt + Number(eachAfterRateAmt);
            }
            var taxRate = $(rows[j]).children('td').eq(7).find('input[name="EachTaxRate"]').val();
            if (taxRate != '' && typeof (taxRate) != 'undefined') {
                var eachprice = 0;
                if (eachCount != 0) {
                    eachprice = eachAfterRateAmt / (taxRate / 100 + 1) / eachCount;
                }
                if(productSn != 1 || SNManage != 1){
                    $(rows[j]).children('td').eq(3).find('input[name="SalePrice"]').val(getSystemDecimal(Number(eachprice)));
                    $(rows[j]).children('td').eq(6).find('input[name="EachSaleAmt"]').val(getSystemDecimal(Number(eachprice * eachCount)));
                }
            }
        }

    }

    try {
        $("#SaleAmt").val(getSystemDecimal(amtCount));
        $("#spanTotalCount").text(getSystemDecimal(totalCount));
        $("#spanTaxAmt").text(getSystemDecimal(rateAmt));
        //计算折后金额
        calDiscountAmt();
    } catch (e) {
        alert(e);
    }
}

function chgNoTaxRate() {
        var isTaxRate = document.getElementsByName("chkNoTaxRate")[0];
        if (isTaxRate.checked) {
            var rows = $("#tabProducts tr");
            for (var j = 0; j < rows.length; j++) {
                var productName = $(rows[j]).children('td').eq(1).find('input[name="showProductName"]').val();
                if (typeof (productName) != 'undefined' && productName != '') {
                    $(rows[j]).children('td').eq(7).find('input').val("0.00");
                    $(rows[j]).children('td').eq(7).find('input').attr("readonly", "readonly");
                    $(rows[j]).children('td').eq(7).find('input').change();
                }
            }
        }
        else {
            var rows = $("#tabProducts tr");
            for (var j = 0; j < rows.length; j++) {
                var productName = $(rows[j]).children('td').eq(1).find('input[name="showProductName"]').val();
                if (typeof (productName) != 'undefined' && productName != '') {
                    $(rows[j]).children('td').eq(7).find('input').val(getSystemDecimal(Number(saleTaxRate)));
                    $(rows[j]).children('td').eq(7).find('input').removeAttr("readonly");
                    $(rows[j]).children('td').eq(7).find('input').change();
                    }
                }
            }
        }


//计算折后金额 默认填充实收金额

function calDiscountAmt() {
    var otherFee = $("#OtherFee").val();
    if (!isNumber(otherFee)) {
        Dialog.alert("其他费用格式不正确");
        return;
    }
    var amtCount = $("#SaleAmt").val();
    var discountRate = $("#DiscountRate").val();
    var discountAmt = (Number(amtCount) * Number(discountRate) / 100);
    $("#DiscountAmt").val(getSystemDecimal(discountAmt));
    if (IsOpenSaleTaxRate == "1") {
        var rows = $("#tabProducts tr");
        discountAmt = 0;
        for (var i = 0; i < rows.length; i++) {
            var eachAmt = $(rows[i]).children('td').eq(6).find('input[name="EachSaleAmt"]').val();
            var eachRate = $(rows[i]).children('td').eq(7).find('input[name="EachTaxRate"]').val();
            if (eachAmt != "" && eachRate != "" && isNumber(eachAmt) && isNumber(eachRate)) {
                var eachSumAmt = Number(eachAmt) * discountRate / 100;
                discountAmt = discountAmt + (Number(eachSumAmt) + Number(eachSumAmt) * Number(eachRate) / 100);
            }
        }
    }
    var faReceAmt = Number(otherFee) + discountAmt;
    $("#FAReceAmt").val(getSystemDecimal(faReceAmt));
    $("#spanFAReceAmt").text(getSystemDecimal(faReceAmt));
        $("#ReceAmt").val(getSystemDecimal(faReceAmt));
       $("#spanTotalTaxAmt").text(getSystemDecimal(Number($("#spanTaxAmt").text()-$("#SaleAmt").val())*Number($("#DiscountRate").val())/100));
      $("#totalTaxAmt").val(getSystemDecimal(Number($("#spanTaxAmt").text()-$("#SaleAmt").val())*Number($("#DiscountRate").val())/100));
}


// 选择商品点击OK处理填充数据

function SelectProductOK(tempJson, obj) {
    var isSelTaxRate = document.getElementsByName("chkNoTaxRate")[0];
    var i = 0, j = 0;
    if (obj != null && tempJson.length > 0) {
        $(obj).children('td').eq(1).find('input[name="showProductName"]').val(tempJson[i]["Name"] + "/" + tempJson[i]["Form"]);
        $(obj).children('td').eq(1).find('input[name="showProductName"]').attr("readonly", "readonly");
        $(obj).children('td').eq(1).find('input[name="showProductName"]').attr("unselectable", "on");
        $(obj).children('td').eq(4).find('input[name="hidSNManage"]').val( tempJson[i]["SNManage"]);
        $(obj).children('td').eq(2).find('input[name="showProductCode"]').val(tempJson[i]["Code"]);
        $(obj).children('td').eq(2).find('input[name="showProductCode"]').attr("readonly", "readonly");
        $(obj).children('td').eq(2).find('input[name="showProductCode"]').attr("unselectable", "on");
        $(obj).children('td').eq(2).find('input[name="hidProductId"]').val(tempJson[i]["ID"]);
        $(obj).children('td').eq(3).find('input[name="SalePrice"]').val(tempJson[i]["SalePrice"]);
        $(obj).children('td').eq(2).find('input[name="hidLowPrice"]').val(tempJson[i]["LowSalePrice"]);
        $(obj).children('td').eq(2).find('input[name="hidStockCount"]').val(tempJson[i]["Store"]);
        if (tempJson[i]["RowId"] != null) {
            $(obj).find('input[name="hidSerialId"]').attr("id", "sn_" + tempJson[i]["RowId"]);
            $(obj).find('input[name="hidSerialId"]').val(tempJson[i]["SerialId"]);
        }
        $(obj).children('td').eq(5).find('input[name="UnitName"]').val(tempJson[i]["Unit"]);
        $(obj).children('td').eq(5).find('input[name="UnitName"]').attr("readonly", "readonly");
        $(obj).children('td').eq(5).find('input[name="UnitName"]').attr("unselectable", "on");
        $(obj).children('td').eq(5).find('input[name="HidUnitCode"]').val(tempJson[i]["UnitCode"]);
        $(obj).children('td').eq(5).find('input[name="HidIsDecimal"]').val(tempJson[i]["IsDecimal"]);
        if(saleTaxRate != 0){
            if(isSelTaxRate.checked){
                $(obj).children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(0)));
                $(obj).children('td').eq(7).find('input').attr("readonly", "readonly");
            }else{
                $(obj).children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(saleTaxRate)));
            }
        }else{
           $(obj).children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(0)));
        }
        if (tempJson[i]["SNManage"] != "0" && productSn == 1) {
            $(obj).children('td').eq(4).find('a[name="aSingleSN"]').show();
        } else {
            $(obj).children('td').eq(4).find('a[name="aSingleSN"]').hide();
        }
        if (tempJson[i]["SNManage"] == "1" && productSn == 1) {
            $(obj).children('td').eq(4).find('input[name="SaleCount"]').attr("readonly", "readonly");
            $(obj).children('td').eq(4).find('input[name="SaleCount"]').attr("unselectable", "on");
            $(obj).children('td').eq(4).find('input[name="SaleCount"]').val(tempJson[i]["SaleCount"]).change();
        } else {
            $(obj).children('td').eq(4).find('input[name="SaleCount"]').removeAttr("readonly");
            $(obj).children('td').eq(4).find('input[name="SaleCount"]').removeAttr("unselectable");
            $(obj).children('td').eq(4).find('input[name="SaleCount"]').val(tempJson[i]["SaleCount"]).change();
        }
        i++;
    }
    for (; i < tempJson.length; i++) {
        var rows = $("#tabProducts tr");
        for (; j < rows.length; j++) {
            if (i >= tempJson.length) break;
            if (rows[j].rowIndex > obj.rowIndex && $(rows[j]).children('td').eq(2).find('input[name="hidProductId"]').length == 1 && $(rows[j]).attr("id") != "trTmp") {
                $(rows[j]).children('td').eq(1).find('input[name="showProductName"]').val(tempJson[i]["Name"] + "/" + tempJson[i]["Form"]);
                $(rows[j]).children('td').eq(1).find('input[name="showProductName"]').attr("readonly", "readonly");
                $(rows[j]).children('td').eq(1).find('input[name="showProductName"]').attr("unselectable", "on");
                $(rows[j]).children('td').eq(4).find('input[name="hidSNManage"]').val( tempJson[i]["SNManage"]);
                $(rows[j]).children('td').eq(2).find('input[name="showProductCode"]').val(tempJson[i]["Code"]);
                $(rows[j]).children('td').eq(2).find('input[name="showProductCode"]').attr("readonly", "readonly");
                $(rows[j]).children('td').eq(2).find('input[name="showProductCode"]').attr("unselectable", "on");
                $(rows[j]).children('td').eq(2).find('input[name="hidProductId"]').val(tempJson[i]["ID"]);
                $(rows[j]).children('td').eq(3).find('input[name="SalePrice"]').val(tempJson[i]["SalePrice"]);
                $(rows[j]).children('td').eq(2).find('input[name="hidLowPrice"]').val(tempJson[i]["LowSalePrice"]);
                $(rows[j]).children('td').eq(2).find('input[name="hidStockCount"]').val(tempJson[i]["Store"]);
                if (tempJson[i]["RowId"] != null) {
                    $(rows[j]).find('input[name="hidSerialId"]').attr("id", "sn_" + tempJson[i]["RowId"]);
                    $(rows[j]).find('input[name="hidSerialId"]').val(tempJson[i]["SerialId"]);
                }
                $(rows[j]).children('td').eq(5).find('input[name="UnitName"]').val(tempJson[i]["Unit"]);
                $(rows[j]).children('td').eq(5).find('input[name="UnitName"]').attr("readonly", "readonly");
                $(rows[j]).children('td').eq(5).find('input[name="UnitName"]').attr("unselectable", "on");
                $(rows[j]).children('td').eq(5).find('input[name="HidUnitCode"]').val(tempJson[i]["UnitCode"]);
                $(rows[j]).children('td').eq(5).find('input[name="HidIsDecimal"]').val(tempJson[i]["IsDecimal"]);
                 if(saleTaxRate != 0){
                      if(isSelTaxRate.checked){
                            $(rows[j]).children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(0)));
                            $(rows[j]).children('td').eq(7).find('input').attr("readonly", "readonly");
                        }else{
                            $(rows[j]).children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(saleTaxRate)));
                        }
                 }else{
                     $(rows[j]).children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(0)));
                 }
                if (tempJson[i]["SNManage"] != "0"&& productSn == 1) {
                    $(rows[j]).children('td').eq(4).find('a[name="aSingleSN"]').show();
                } else {
                    $(rows[j]).children('td').eq(4).find('a[name="aSingleSN"]').hide();
                }
                if (tempJson[i]["SNManage"] == "1"&& productSn == 1) {
                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').attr("readonly", "readonly");
                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').attr("unselectable", "on");
                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').val(tempJson[i]["SaleCount"]).change();
                } else {
                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').removeAttr("readonly");
                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').removeAttr("unselectable");
//                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').val(1).change();
                    $(rows[j]).children('td').eq(4).find('input[name="SaleCount"]').val(tempJson[i]["SaleCount"]).change();
                }
                i++;
            }
        }
        if (i < tempJson.length) {
            var trTmp = $("#trTmp").clone();
            trTmp.attr("id", "");
            trTmp.show();
            trTmp.children('td').eq(1).find('input[name="showProductName"]').val(tempJson[i]["Name"] + "/" + tempJson[i]["Form"]);
            trTmp.children('td').eq(1).find('input[name="showProductName"]').attr("readonly", "readonly");
            trTmp.children('td').eq(1).find('input[name="showProductName"]').attr("unselectable", "on");
            trTmp.children('td').eq(4).find('input[name="hidSNManage"]').val( tempJson[i]["SNManage"]);
            trTmp.children('td').eq(2).find('input[name="showProductCode"]').val(tempJson[i]["Code"]);
            trTmp.children('td').eq(2).find('input[name="showProductCode"]').attr("readonly", "readonly");
            trTmp.children('td').eq(2).find('input[name="showProductCode"]').attr("unselectable", "on");
            trTmp.children('td').eq(2).find('input[name="hidProductId"]').val(tempJson[i]["ID"]);
            trTmp.children('td').eq(3).find('input[name="SalePrice"]').val(tempJson[i]["SalePrice"]);
            trTmp.children('td').eq(2).find('input[name="hidLowPrice"]').val(tempJson[i]["LowSalePrice"]);
            trTmp.children('td').eq(2).find('input[name="hidStockCount"]').val(tempJson[i]["Store"]);
            if (tempJson[i]["RowId"] != null) {
                trTmp.find('input[name="hidSerialId"]').attr("id", "sn_" + tempJson[i]["RowId"]);
                trTmp.find('input[name="hidSerialId"]').val(tempJson[i]["SerialId"]);
            }
            trTmp.children('td').eq(5).find('input[name="UnitName"]').val(tempJson[i]["Unit"]);
            trTmp.children('td').eq(5).find('input[name="UnitName"]').attr("readonly", "readonly");
            trTmp.children('td').eq(5).find('input[name="UnitName"]').attr("unselectable", "on");
            trTmp.children('td').eq(5).find('input[name="HidUnitCode"]').val(tempJson[i]["UnitCode"]);
            trTmp.children('td').eq(5).find('input[name="HidIsDecimal"]').val(tempJson[i]["IsDecimal"]);
            if(saleTaxRate != 0){
                   if(isSelTaxRate.checked){
                        trTmp.children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(0)));
                        trTmp.children('td').eq(7).find('input').attr("readonly", "readonly");
                    }else{
                        trTmp.children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(saleTaxRate)));
                        }
            }else{
                     trTmp.children('td').eq(7).find('input[name="EachTaxRate"]').val(getSystemDecimal(Number(0)));
            }
            if (tempJson[i]["SNManage"] != "0"&& productSn == 1) {
                trTmp.children('td').eq(4).find('a[name="aSingleSN"]').show();
            } else {
                trTmp.children('td').eq(4).find('a[name="aSingleSN"]').hide();
            }
            if (tempJson[i]["SNManage"] == "1"&& productSn == 1) {
                trTmp.children('td').eq(4).find('input[name="SaleCount"]').attr("readonly", "readonly");
                trTmp.children('td').eq(4).find('input[name="SaleCount"]').attr("unselectable", "on");
                trTmp.children('td').eq(4).find('input[name="SaleCount"]').val(tempJson[i]["SaleCount"]).change();
            } else {
                trTmp.children('td').eq(4).find('input[name="SaleCount"]').removeAttr("readonly");
                trTmp.children('td').eq(4).find('input[name="SaleCount"]').removeAttr("unselectable");
//                trTmp.children('td').eq(4).find('input[name="SaleCount"]').val(1).change();
                trTmp.children('td').eq(4).find('input[name="SaleCount"]').val(tempJson[i]["SaleCount"]).change();
            }
            trTmp.insertBefore($("#trTmp"));
        }
    }
    if ($("#tabProducts tr[id!='trTmp']").find("input:text[autoComplete='off']").length < 1) {
        addRow();
    }
    //计算总金额
    calCountAmt();
    InitOrder();
    $("#tabProducts tr").mouseover(function () {
        $(this).find('.choseGoods').show();
    }).mouseout(function () {
                $(this).find('.choseGoods').hide();
            })
}

//单行计算金额
function calSaleAmt(obj) {
    //验证单位
    var unitName = $(obj).parent().parent().children('td').eq(4).find('span').html();//数量
//    alert(unitName)
    var isDecimal = $(obj).parent().parent().children('td').eq(7).find('input[type="hidden"]').val();//税率
    //验证最低销售和最高销售价
    var isCheckLowPrice = "0";
    var lowPrice = $(obj).parent().parent().children('td').eq(2).find('input[name="hidLowPrice"]').val();//商品编号
    var highPrice = $(obj).parent().parent().children('td').eq(9).text();//备注
    //验证税率
    var isOpenTax = IsOpenSaleTaxRate;
    var TaxRate = $(obj).parent().parent().children('td').eq(7).find('input').val();
    //var salePrice = obj.parentNode.parentNode.cells[2].childNodes[0].value;
    var salePrice = $(obj).parent().parent().children('td').eq(3).find('input').val();//单价
    var saleCount = $(obj).parent().parent().children('td').eq(4).find('input').val();
    //var curStock = obj.parentNode.parentNode.cells[0].childNodes[2].value;
    var curStock = $(obj).parent().parent().children('td').eq(2).find('input[name="hidStockCount"]').val();
    $(obj).parent().parent().children('td').eq(6).find('input').val(getSystemDecimal((Number(salePrice) * Number(saleCount))));//6金额
    //验证单位
    if (isDecimal == "0" && !isInteger(saleCount)) {
        Dialog.alert('单位为 ' + unitName + ' 时， 数量必须输入整数！', function () {
            $(obj).parent().parent().children('td').eq(4).find('input').val("");
            $(obj).parent().parent().children('td').eq(4).find('input').focus();
            return;
        });
    }
    //验证最低销售和最高销售价
    if (isCheckLowPrice == "1" && isNumber(lowPrice) && isNumber(salePrice) && Number(lowPrice) != 0 && Number(salePrice) < Number(lowPrice)) {
        Dialog.alert('单价不能低于最低销售价！', function () {
            $(obj).parent().parent().children('td').eq(3).find('input').val("");
            $(obj).parent().parent().children('td').eq(3).find('input').focus();
            return;
        });
    }
    if (isOpenTax == "1") {
        //验证税率
        if (TaxRate == "" || !isNumber(TaxRate) || Number(TaxRate) < 0 || Number(TaxRate) > 100) {
            Dialog.alert("税率必须为0-100的数字！");
            $(obj).parent().parent().children('td').eq(7).find('input').val("0");
            $(obj).parent().parent().children('td').eq(7).find('input').focus();
            return;
        }
        if (isNumber(TaxRate) && TaxRate != "")
            $(obj).parent().parent().children('td').eq(8).find('input').val(getSystemDecimal(((Number(salePrice) * Number(saleCount)) + (Number(salePrice) * Number(saleCount) * Number(TaxRate) / 100))));
    }
    //计算总金额
    calCountAmt();
    //库存提醒
    if (Number(saleCount) > Number(curStock)) {
        if (GetNegativeInventory() == "0") {
            Dialog.alert("当前商品的库存数量小于您所输入的商品数量！");
            //$(obj).parent().parent().children('td').eq(4).find('input').val("");
            $(obj).parent().parent().children('td').eq(4).find('input').css("color", "red").css("font-weight", "700");
        }
    } else {
        $(obj).parent().parent().children('td').eq(4).find('input').css("color", "#000").css("font-weight", "normal");
    }
    //单价提醒
    if(IsCheckSalePrice == '1'){
        if (Number(lowPrice) > Number(salePrice)) {
                $(obj).parent().parent().children('td').eq(3).find('input').css("color", "red").css("font-weight", "700");
                Dialog.alert("商品单价低于最低售价！", function () {
            });
          }else{
            $(avg).parent().parent().children('td').eq(3).find('input').css("color", "#000").css("font-weight", "normal");
        }
    }

    $(obj).parent().parent().children('td').eq(3).find('input').val(getSystemDecimal(Number(salePrice)));
    $("#spanTotalTaxAmt").text(getSystemDecimal(Number($("#spanTaxAmt").text()-$("#SaleAmt").val())*Number($("#DiscountRate").val())/100));
    $("#totalTaxAmt").val(getSystemDecimal(Number($("#spanTaxAmt").text()-$("#SaleAmt").val())*Number($("#DiscountRate").val())/100));
}

function GetNegativeInventory() {
    var NIVal = -1;
   // var sysconf = getSysConfig();
   // sysconf = eval("(" + sysconf + ")");
    NIVal = sysconf['IsAllowNegativeInventory'];
    return NIVal;
}

//单行根据总金额和数量计算单价
function calSalePrice(obj) {
    //验证税率
    var isOpenTax = IsOpenSaleTaxRate;
    var TaxRate = $(obj).parent().parent().children('td').eq(7).find('input').val();
    var saleCount = $(obj).parent().parent().children('td').eq(4).find('input').val();
    var saleAmt = $(obj).parent().parent().children('td').eq(6).find('input').val();
    var salePrice = 0;
    if (saleCount != "" && Number(saleCount) != 0) {
        $(obj).parent().parent().children('td').eq(3).find('input').val(getSystemDecimal(Number(saleAmt) / Number(saleCount)));
        salePrice = Number(saleAmt) / Number(saleCount);
    }
    if (isOpenTax == "1") {
        //验证税率
        if (TaxRate == "" || !isNumber(TaxRate) || Number(TaxRate) < 0 || Number(TaxRate) > 100) {
            Dialog.alert("税率必须为0-100的数字！");
            $(obj).parent().parent().children('td').eq(7).find('input').val("0");
            $(obj).parent().parent().children('td').eq(7).find('input').focus();
            return;
        }
        if (isNumber(TaxRate) && TaxRate != "")
            $(obj).parent().parent().children('td').eq(8).find('input').val(getSystemDecimal((salePrice * Number(saleCount)) + (salePrice * Number(saleCount) * Number(TaxRate) / 100)));
    }
    calCountAmt();
}

//计算折扣率 默认填充实收金额
function calDiscountRate() {
    var otherFee = $("#OtherFee").val();
     var amtCount = $("#SaleAmt").val();
    var discountAmt = $("#DiscountAmt").val();
    var discountRate = 0;
    if (Number(amtCount) != 0) {
        discountRate = (Number(discountAmt) / Number(amtCount) * 100);
    }
    if (IsOpenSaleTaxRate == "1") {
        var rows = $("#tabProducts tr");
        discountAmt = 0;
        for (var i = 0; i < rows.length; i++) {
            var eachAmt = $(rows[i]).children('td').eq(6).find('input[name="EachSaleAmt"]').val();
            var eachRate = $(rows[i]).children('td').eq(7).find('input[name="EachTaxRate"]').val();
            if (eachAmt != "" && eachRate != "" && isNumber(eachAmt) && isNumber(eachRate)) {
                var eachSumAmt = Number(eachAmt) * discountRate / 100;
                discountAmt = discountAmt + (Number(eachSumAmt) + Number(eachSumAmt) * Number(eachRate) / 100);
            }
        }
    }
    var faReceAmt = Number(otherFee) + Number(discountAmt);
    $("#DiscountRate").val(getSystemDecimal(discountRate));
    $("#FAReceAmt").val(getSystemDecimal(faReceAmt));
    $("#spanFAReceAmt").text(getSystemDecimal(faReceAmt));
    $("#ReceAmt").val(getSystemDecimal(faReceAmt));
    $("#spanTotalTaxAmt").text(getSystemDecimal(Number($("#spanTaxAmt").text()-$("#SaleAmt").val())*Number($("#DiscountRate").val())/100));
    $("#totalTaxAmt").val(getSystemDecimal(Number($("#spanTaxAmt").text()-$("#SaleAmt").val())*Number($("#DiscountRate").val())/100));
}

//其他费用
function calOtherFeeAmt() {
    var otherFee = $("#OtherFee").val();
    if (!isNumber(otherFee)) {
        Dialog.alert("其他费用格式不正确");
        return;
    }
    var amtCount = $("#SaleAmt").val();

    var discountRate = $("#DiscountRate").val();
    var discountAmt = (Number(amtCount) * Number(discountRate) / 100);
    $("#DiscountAmt").val(getSystemDecimal(discountAmt));
    if (IsOpenSaleTaxRate == "1") {
        var rows = $("#tabProducts tr");
        discountAmt = 0;
        for (var i = 0; i < rows.length; i++) {
            var eachAmt = $(rows[i]).children('td').eq(6).find('input[name="EachSaleAmt"]').val();
            var eachRate = $(rows[i]).children('td').eq(7).find('input[name="EachTaxRate"]').val();
            if (eachAmt != "" && eachRate != "" && isNumber(eachAmt) && isNumber(eachRate)) {
                var eachSumAmt = Number(eachAmt) * discountRate / 100;
                discountAmt = discountAmt + (Number(eachSumAmt) + Number(eachSumAmt) * Number(eachRate) / 100);
            }
        }
    }
    var faReceAmt = Number(otherFee) + discountAmt;
        $("#FAReceAmt").val(getSystemDecimal(faReceAmt));
        $("#spanFAReceAmt").text(getSystemDecimal(faReceAmt));
        $("#ReceAmt").val(getSystemDecimal(faReceAmt));
    }

//验证最低销售单价
function checkSalePrice(avg){
    var salePrice = $(avg).val();
    var productHid = $(avg).parent().parent().children('td').eq(2).find('input[name="hidProductId"]').val();
    var lowPrice = $(avg).parent().parent().children('td').eq(2).find('input[name="hidLowPrice"]').val();
      if(IsCheckSalePrice == '1'){
            if (productHid != "" && Number(lowPrice) > Number(salePrice)) {
                $(avg).parent().parent().children('td').eq(3).find('input').css("color", "red").css("font-weight", "700");
                Dialog.alert("商品单价低于最低售价！", function () {
                });
              }else{
                $(avg).parent().parent().children('td').eq(3).find('input').css("color", "#000").css("font-weight", "normal");
            }
        }
}

    //当仓库改变时，验证库存
  function WarehouseChaneg(){
        if (GetNegativeInventory() == "0") {
            var productHid = $("input:hidden[name='hidProductId']");
            var saleCountList = $("input:text[name='SaleCount']");
            var reqJson = {};
            var temp_productHid = [];
            var temp_saleCount = [];
            var saleCountObj = [];
            for(var i = 0; i < productHid.length; i ++){
                if(productHid[i].value != ""){
                    temp_productHid.push(productHid[i].value)
                    temp_saleCount.push(saleCountList[i].value)
                    saleCountObj.push(saleCountList[i]);
                }
            }

            reqJson["ProductIdList"] = temp_productHid
            reqJson["WarehouseId"] = $("#WarehouseId").val();
            var result = parent.product_bi.getProductCountListByWarehouse(JSON.stringify(reqJson));
            var resultList = eval("(" + result +")");
            var j = 0;
            for(var i = 0; i < temp_productHid.length; i++){
                if(Number(resultList[temp_productHid[i]]) < Number(temp_saleCount[i])){
                   $(saleCountObj[i]).css("color", "red").css("font-weight", "700");
                    j++;
                }else{
                     $(saleCountObj[i]).css("color", "#000").css("font-weight", "normal");
                }
             }
            if(j > 0){
                Dialog.alert("当前商品的库存数量小于您所输入的商品数量！");
                return false;
            }
        }
        return true;
    }
//提交表单验证
function ValidateForm() {
    var isOpenTax = IsOpenSaleTaxRate;
    //单据编号
    if ($("#SaleNo").val().trim() == "") {
        $("#SaleNo")[0].focus();
        Dialog.alert("请输入单据编号。", function () {
            $("#SaleNo").addClass("input-validation-error");
        });
        return false;
    }
    if (!CheckWord($("#SaleNo").val().trim())) {
        $("#SaleNo").addClass("input-validation-error");
        return false;
    }
    if (ValidateNo($("#SaleNo").val()) == "0") {
        Dialog.alert("单据编号重复。", function () {
            $("#SaleNo").addClass("input-validation-error");
        });
        $('#SaleNo')[0].focus();
        return false;
    }
    //客户
    if($("#ClientId").val() == null){
        Dialog.alert("请选择客户！")
        return false;
    }
        if ($("#ClientId").val().trim() == '' || $("#ClientId").val().trim() == '00000000-0000-0000-0000-000000000000') {
            Dialog.alert("请输入客户。", function () {
                $("#ClientId").addClass("input-validation-error");
            });
            return false;
        } else {
            $("#ClientId").removeClass("input-validation-error");
        }
    //经手人
    if ($("#SaleUser").val() == '') {
        Dialog.alert("请选择经手人。", function () {
            $("#SaleUser").addClass("input-validation-error");
        });
        return false;
    }
    //业务日期
    if ($("#SaleDate").val() == '') {
        Dialog.alert("请选择业务日期。", function () {
            $("#SaleDate").addClass("input-validation-error");
        });
        return false;
    }
    if(productSn==1&&!varlidatorSerialNo("hidSerialId")){
        Dialog.alert("您选择了相同商品，并且序列号有重复，请重新选择。");
        return false;
    }
    //验证无效的商品并提示
    var hasEmptyPro = false;
    var allCompleteTr = $("#tabProducts tr[id!='trTmp']").has("input:text[autoComplete='off']");
    for (var i = 0; i < allCompleteTr.length; i++) {
        var curtr = $(allCompleteTr[i]);
        var pid = curtr.find("input:hidden[name='hidProductId']").first().val();
        var isEmptyPro = curtr.find("input:text[autoComplete='off'][value!='']").length > 0;
        if (pid == "" && isEmptyPro) {
            curtr.find("input:text[autoComplete='off']").css({ "border": "#ff0000 1px solid" });
            hasEmptyPro = true;
        }
    }
    if (hasEmptyPro) {
        Dialog.alert("商品列表中存在无效的商品。");
        return false;
    }
    //验证是否选择了商品
    var productHid = $("input:hidden[name='hidProductId']");
    //验证单价
    var salePriceList = $("input:text[name='SalePrice']");
    //验证数量
    var saleCountList = $("input:text[name='SaleCount']");
    //当前库存
    var stockCountList = $("input:hidden[name='hidStockCount']");
    //验证最低售价
    var lowPriceList = $("input:hidden[name='hidLowPrice']");
    //验证税率
    var isOpenTax = IsOpenSaleTaxRate;
    var TaxRateList = $("input:text[name='EachTaxRate']");
    //验证单位
    var unitNameList = $("input:text[name='UnitName']");
    var unitIsDecimal = $("input:hidden[name='HidIsDecimal']");
    var tempHidValue = "";
    //已选择的商品idList
    var productHidList = [];
    var productHidObj = [];
    var tempSaleCountBool = true;
    for (var i = 0; i < productHid.length; i++) {
        if(productHid[i].value != ''){
            productHidList.push(productHid[i].value);
            productHidObj.push(productHid[i]);
        }
        tempHidValue = tempHidValue + productHid[i].value;
        if (productHid[i].value != "" && (salePriceList[i].value == "" || Number(salePriceList[i].value) < 0)) {
            salePriceList[i].value = "";
            Dialog.alert("商品单价必填并且不能小于0。", function () {
                $(salePriceList[i]).focus();
                $(salePriceList[i]).css({
                    "border-bottom": "#fff000 1px solid",
                    "border-left": "#fff000 1px solid",
                    "border-right": "#fff000 1px solid",
                    "border-top": "#fff000 1px solid"
                });
            });
            return false;
        }
        if(IsCheckSalePrice == '1'){
            if (Number(lowPriceList[i].value) > Number(salePriceList[i].value)) {
                Dialog.alert("商品单价低于最低售价！", function () {
                    $(salePriceList[i]).focus();
                    $(salePriceList[i]).css({
                        "border-bottom": "#fff000 1px solid",
                        "border-left": "#fff000 1px solid",
                        "border-right": "#fff000 1px solid",
                        "border-top": "#fff000 1px solid"
                    });
                });
              }
        }
        if (Number(salePriceList[i].value) > 9999999999) {
            salePriceList[i].value = "";
            Dialog.alert("商品单价数值超出合理的范围。", function () {
                $(salePriceList[i]).focus();
                $(salePriceList[i]).css({
                    "border-bottom": "#fff000 1px solid",
                    "border-left": "#fff000 1px solid",
                    "border-right": "#fff000 1px solid",
                    "border-top": "#fff000 1px solid"
                });
            });
            return false;
        }
        if (productHid[i].value != "" && (saleCountList[i].value == "" || Number(saleCountList[i].value) <= 0)) {
            saleCountList[i].value = "";
            Dialog.alert("商品数量必填并且大于0。", function () {
                $(saleCountList[i]).css({
                    "border-bottom": "#fff000 1px solid",
                    "border-left": "#fff000 1px solid",
                    "border-right": "#fff000 1px solid",
                    "border-top": "#fff000 1px solid"
                });
                $(saleCountList[i]).focus();
            });
            return false;
        }
        if (Number(saleCountList[i].value) > 9999999999) {
            saleCountList[i].value = "";
            Dialog.alert("商品数量数值超出合理的范围。", function () {
                $(saleCountList[i]).css({
                    "border-bottom": "#fff000 1px solid",
                    "border-left": "#fff000 1px solid",
                    "border-right": "#fff000 1px solid",
                    "border-top": "#fff000 1px solid"
                });
                $(saleCountList[i]).focus();
            });
            return false;
        }
        if (unitIsDecimal[i].value == "0" && !isInteger(saleCountList[i].value)) {
            Dialog.alert('单位为 ' + $(unitNameList[i]).val() + ' 时， 数量必须输入整数！',
                    function () {
                        $(saleCountList[i]).focus();
                    });
            return false;
        }
        if (isOpenTax == "1") {
            //验证税率
            if (!isNumber(TaxRateList[i].value) || Number(TaxRateList[i].value) < 0 || Number(TaxRateList[i].value) > 100) {
                Dialog.alert('税率必须为0-100的数字！');
                $(TaxRateList[i]).focus();
                return false;
            }
        }
    }

    var reqJosn1 = {};
    reqJosn1["ProductIdList"] = productHidList;
    var result1 = parent.product_bi.judgeGoodsIsStopOrDel(JSON.stringify(reqJosn1));
    var resultList1 = eval("("+ result1 +")");
    var data = resultList1["Data"];
    var judgeGoodsIsStopOrDelIndex = 0;
    for(var i = 0; i < productHidList.length; i ++){
        if(data[productHidList[i]] == '0'){
            $(productHidObj[i]).parent().parent().children('td').find('input[name="showProductName"]').css("color", "red").css("font-weight", "700");
            Dialog.alert("选择的商品已被删除或停用！")
            judgeGoodsIsStopOrDelIndex++;
        }else{
             $(productHidObj[i]).parent().parent().children('td').find('input[name="showProductName"]').css("color", "#000").css("font-weight", "normal");
         }
    }
    if(judgeGoodsIsStopOrDelIndex > 0){
        return false;
    }

    if (tempHidValue == "") {
        Dialog.alert("请选择商品。");
        return false;
    }
    //总金额
    if (!isNumber($("#SaleAmt").val())) {
        Dialog.alert("合计金额格式不正确。", function () {
            $("#SaleAmt").addClass("input-validation-error");
        });
        return false;
    }
    if (Number($("#SaleAmt").val()) > 9999999999) {
        Dialog.alert("合计金额值超出合理的范围。", function () {
            $("#SaleAmt").addClass("input-validation-error");
        });
        return false;
    }
    $("#SaleAmt").removeClass("input-validation-error");
    //折扣率
    if ($("#DiscountRate").val().trim() == '') {
        Dialog.alert("请输入折扣率。", function () {
            $("#DiscountRate").addClass("input-validation-error");
        });
        return false;
    }
    if (!isNumber($("#DiscountRate").val())) {
        Dialog.alert("折扣率格式不正确。", function () {
            $("#DiscountRate").addClass("input-validation-error");
        });
        return false;
    }
    if (Number($("#DiscountRate").val()) > 9999999999) {
        Dialog.alert("折扣率超出合理的范围。", function () {
            $("#DiscountRate").addClass("input-validation-error");
        });
        return false;
    }
    $("#DiscountRate").removeClass("input-validation-error");
    //折后实收
    if ($("#DiscountAmt").val().trim() == '') {
        Dialog.alert("请输入折后实收。", function () {
            $("#DiscountAmt").addClass("input-validation-error");
        });
        return false;
    }
    if (!isNumber($("#DiscountAmt").val())) {
        Dialog.alert("折后实收格式不正确。", function () {
            $("#DiscountAmt").addClass("input-validation-error");
        });
        return false;
    }
    if (Number($("#DiscountAmt").val()) > 9999999999) {
        Dialog.alert("折后实收超出合理的范围。", function () {
            $("#DiscountAmt").addClass("input-validation-error");
        });
        return false;
    }
    $("#DiscountAmt").removeClass("input-validation-error");
    //收款账户
    if ($("#AccountId").val() == '' || $("#AccountId").val() == null) {
        Dialog.alert("请选择结算方式。", function () {
            $("#AccountId").addClass("input-validation-error");
        });
        return false;
    }
    $("#AccountId").removeClass("input-validation-error");
    //其他费用
    if ($("#OtherFee").val().trim() == '') {
        $("#OtherFee").val('0');
    }
    if (!isNumber($("#OtherFee").val())) {
        Dialog.alert("其他费用格式不正确。", function () {
            $("#OtherFee").addClass("input-validation-error");
        });
        return false;
    }
    if (Number($("#OtherFee").val()) > 9999999999) {
        Dialog.alert("其他费用超出合理的范围。", function () {
            $("#OtherFee").addClass("input-validation-error");
        });
        return false;
    }
    $("#OtherFee").removeClass("input-validation-error");
    //实收金额
    if ($("#ReceAmt").val().trim() == '') {
        Dialog.alert("请输入实收金额。", function () {
            $("#ReceAmt").addClass("input-validation-error");
        });
        return false;
    }
    if (!isNumber($("#ReceAmt").val())) {
        Dialog.alert("实收金额格式不正确。", function () {
            $("#ReceAmt").addClass("input-validation-error");
        });
        return false;
    }
    if (Number($("#ReceAmt").val()) > 9999999999) {
        Dialog.alert("实收金额超出合理的范围。", function () {
            $("#ReceAmt").addClass("input-validation-error");
        });
        return false;
    }
    if(!WarehouseChaneg()){
        return false;
    }
    $("#ReceAmt").removeClass("input-validation-error");
    return true;
}


function ValidateNo(saleNo) {
    var NIVal = -1;
    var reqJson = {};
        reqJson["SaleNo"] = saleNo;
        var result =  parent.sale_bi.validateSaleNo(JSON.stringify(reqJson));
        var resultList = eval("(" + result + ")");
        if(resultList["IsSuccess"] == "0"){
            NIVal = 0;
        }
    return NIVal;
}

function SaveDataToList(param) {
    $(".button").hide();
     var form_data = {};
    //验证打印权限
    try {
        var isAudit = checkPermByCode('PERM_PRINT');
        if (ValidateForm() && validateSobState()) {
            $("#IsToList").val(1);
            var form = $("#form");
            form_data = getSaveData();
            //输出选择的值
            if (isAudit) {
                var isPrint = $("#chkPrint").attr("checked");
                if (isPrint) {
                    $("#IsPrint").val(1);
                } else {
                    $("#IsPrint").val(0);
                }
            } else {
                $(".button").show();
            }
        var recordList = parent.sale_bi.saveSale(JSON.stringify(form_data));

        var result = eval("(" + recordList + ")");
            if(result["IsSuccess"] == 1){

                if(param == 0){
                    parent.childAddTab('销售历史','Sale/List.html','慧管货');
                    parent.CloseTabByTitle("新增销售");
                }else if(param == 1){
                    parent.childAddTab('新增销售','Sale/Add.html','慧管货');
                }

            }else{
                Dialog.alert(result["Message"])
                parent.childAddTab('销售历史','Sale/List.html','慧管货');
                parent.CloseTabByTitle("新增销售");
            }
            parent.CloseTabByTitle("复制新增销售单");
        } else {
            copyAdd = requestUrlPara("list");
            if(copyAdd == "copyAdd")
            $(".button[id!='add']").show();
            else
            $(".button[id!='copyAdd']").show();
        }


    } catch (e) {
        alert(e);
    }
}

    //获取要保存的数据
    function getSaveData(){
        var form_data = {};
        var eachRowDataArray = [];
        var len = $("#trTmp").siblings("tr").length;
        var trData = $("#trTmp").siblings("tr");
        var index = 0;
        for (var i = 1; i < trData.length-2; i++){
            var serialIds = [];
            var eachRowData = {};
            if($(trData[i]).find('input[name="hidProductId"]').val() != ""){
                eachRowData["ProductId"] = $(trData[i]).find('input[name="hidProductId"]').val();
                eachRowData["SalePrice"] = $(trData[i]).find("input[name='SalePrice']").val();
                eachRowData["ProductUnit"] = $(trData[i]).find("input[name='HidUnitCode']").val();
                eachRowData["SaleCount"] = $(trData[i]).find("input[name='SaleCount']").val();
                eachRowData["SaleAmt"] = $(trData[i]).find("input[name='EachSaleAmt']").val();
                eachRowData["SaleRemark"] = $(trData[i]).find("input[name='EachSaleRemark']").val();
                if(IsOpenSaleTaxRate == '1'){
                    eachRowData["TaxRate"] = $(trData[i]).find("input[name='EachTaxRate']").val();
                    eachRowData["AfterTaxAmt"] = $(trData[i]).find("input[name='EachAfterTaxAmt']").val();
                    eachRowData["TaxAmt"] = eachRowData["AfterTaxAmt"] - eachRowData["SaleAmt"];
                }
                if(productSn == 1){
                    serialIds = $(trData[i]).find("input[name='hidSerialId']").val().split(",");
                    eachRowData["SerialIds"] = serialIds;
                }
            }else{
                continue;
            }
            eachRowDataArray[index] = eachRowData;
            index++;
        }
        form_data["Data"] = eachRowDataArray;
        var ClientId = ($('#ClientId').val()) == null?"":$('#ClientId').val();
        form_data["ClientId"] = ClientId;
        form_data["FAReceAmt"] = $("#spanFAReceAmt").text();
        form_data["ReceAmt"] = $("#ReceAmt").val();
        form_data["SaleRemark"] = $("#SaleRemark").val();
        form_data["SaleNo"] = $("#SaleNo").val()
        form_data["WarehouseId"] = document.getElementById("WarehouseId").value
        form_data["SaleUser"] = $("#SaleUser").val();
        form_data["SaleDate"] = $("#SaleDate").val();
        form_data["SaleAmt"] = $("#SaleAmt").val();
        form_data["DiscountRate"] = $("#DiscountRate").val();
        form_data["DiscountAmt"] = $("#DiscountAmt").val();
        form_data["OtherFee"] = $("#OtherFee").val();
        form_data["AccountId"] = $("#AccountId").val();
        form_data["IsOpenSaleTaxRate"] = IsOpenSaleTaxRate;

    //是否送货，并判断是否是否同步客户信息
        form_data["IsUpdateClientInfo"] = "0";
        var clientInfo = {};
        if(document.getElementsByName("IsNeedDeliverGoods")[0].checked){
            form_data["ClientLink"] = $("#ClientLink").val();
            form_data["ClientTel"] = $("#ClientTel").val();
            form_data["ReceAddress"] = $("#ReceAddress").val();
            form_data["ReceDate"] = $("#ReceDate").val();
            if(document.getElementsByName("IsUpdateClientCon")[0].checked){
                clientInfo["ClientLink"] = $("#ClientLink").val();
                clientInfo["ClientTel"] = $("#ClientTel").val();
                clientInfo["ClientAddress"] = $("#ReceAddress").val();
                form_data["IsUpdateClientInfo"] = "1";
            }
        }
        form_data["ClientInfo"] = clientInfo;
        return form_data;
    }
</script>